package com.cavy.platform.server.validator;

import com.cavy.platform.server.BeansProvider;
import com.cavy.platform.server.repository.PluginRepository;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 验证插件存在
 */
public class PluginExistValidator implements ConstraintValidator<PluginExist, PluginExistData> {
    private PluginRepository bean;

    @Override
    public void initialize(PluginExist notRepeatPluginName) {
        bean = BeansProvider.getBean(PluginRepository.class);
    }

    @Override
    public boolean isValid(PluginExistData dto, ConstraintValidatorContext context) {
        if (dto == null) {
            return true;
        }
        long count = bean.countByName(dto.getName(), dto.getVersion());
        if (count <= 0) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate()).addPropertyNode(dto.getPluginPropertyName()).addConstraintViolation();
            return false;
        }
        return true;
    }
}
